#include "findDialog.h"
#include "ui_findDialog.h"
#include <QDebug>
#include <QString>
#include <QTextCursor>
#include <QMessageBox>


findDialog::findDialog(QWidget *parent, QPlainTextEdit* pText) :
    QDialog(parent), ui(new Ui::findDialog), mEdit(pText)
{
    ui->setupUi(this);
    setQPlainTextEdit(pText);
    ui->checkBoxFindNext->setChecked(true);
    qDebug() << mEdit;
    qDebug() << pText;
}

findDialog::~findDialog()
{
    delete ui;
}

void findDialog::on_findBtn_clicked()
{
    qDebug() << "find btn";
    QString target = ui->findLineEdit->text();
    qDebug() << target;
    if((this->getQPlainTextEdit() != NULL) && (target != " ")) {
        QString text = this->getQPlainTextEdit()->toPlainText();
        QTextCursor c = this->getQPlainTextEdit()->textCursor();
        int index = -1;
        if(ui->checkBoxFindNext->isChecked()) { // 前找
            index = text.lastIndexOf(target, c.position() - target.length() - 1, ui->MatchCaseCheckBox->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive);
            qDebug() << index;
            if (index >= 0) {
                c.setPosition(index + target.length());
                c.setPosition(index, QTextCursor::KeepAnchor);
                this->getQPlainTextEdit()->setTextCursor(c);
            }
        }

        if (ui->checkBoxFindPre->isChecked()) { // 后找
            index = text.indexOf(target,  c.position(),  ui->MatchCaseCheckBox->isChecked()? Qt::CaseSensitive : Qt::CaseInsensitive);
            qDebug() << index << " " << c.position();
            if (index >= 0) {
                c.setPosition(index);
                c.setPosition(index + target.length(), QTextCursor::KeepAnchor);
                this->getQPlainTextEdit()->setTextCursor(c);
            }
        }

        if (index < 0) {
            QMessageBox msg(this);
            msg.setWindowTitle("find");
            msg.setText("no more" + target);
            msg.setIcon(QMessageBox::Critical);
            msg.setStandardButtons(QMessageBox::Ok);
            msg.exec();
        }
    }
    return;
}

void findDialog::on_closeBtn_clicked()
{
    qDebug() << "close btn";
    this->close();
}

void findDialog::setQPlainTextEdit(QPlainTextEdit *pText) {
    mEdit = pText;
    return;
}

QPlainTextEdit* findDialog::getQPlainTextEdit() {
    return mEdit;
}


